package masterjava.soa.smsgate;

import com.sun.xml.ws.developer.SchemaValidation;
import masterjava.common.client.EjbClient;
import masterjava.common.configuration.AppSetting;
import masterjava.common.ws.ValidationHandler;
import masterjava.common.ws.WebServiceFault;
import masterjava.soa.smsgate.type.SenderType;

import javax.annotation.Resource;
import javax.jws.HandlerChain;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;

/**
 * User: GKislin
 * Date: 12.01.2011
 */

@WebService(serviceName = "SmsGateService",
        targetNamespace = "http://smsgate.masterjava.soa.masterjava",
        wsdlLocation = "WEB-INF/wsdl/SmsGateService.wsdl",
        portName = "SmsGateServicePort")
@SchemaValidation(handler = ValidationHandler.class)
@HandlerChain(file = "wsHandlers.xml")

public class SmsGateService implements SmsGate {

    @Resource
    WebServiceContext wsContext;

    private EjbClient<ISmsProvider> smsProvider =
            new EjbClient<ISmsProvider>(SmsGateSetting.get().EJB_PROVIDER.get());

    @Override
    public void sendConfirmCode(String phone) throws WebServiceFault {
        ValidationHandler.validate(wsContext);
        smsProvider.get().sendSms(
                AppSetting.get().COMPANY_NAME.get(),
                phone, "Ваш проверочный код: " + generateCode(phone));
    }

    private String generateCode(String phone) {
        int code = Math.abs(("FD#%&hyh!(#GH" + phone).hashCode()) % 10000;
        return String.format("%04d", code);
    }

    @Override
    public boolean checkConfirmCode(String phone, String code) throws WebServiceFault {
        ValidationHandler.validate(wsContext);
        return code.equals(generateCode(phone));
    }

    @Override
    public void sendSms(SenderType sender, String phone, String message) throws WebServiceFault {
        ValidationHandler.validate(wsContext);
        smsProvider.get().sendSms(
                sender.getSenderName() != null ? sender.getSenderName() : sender.getSenderPhone(),
                phone, message);
    }
}
